/*
https://leetcode-cn.com/problems/frequency-of-the-most-frequent-element/solution/zui-gao-pin-yuan-su-de-pin-shu-by-leetco-q5g9/
 */
import java.util.Arrays;

public class Solution1838 {
    public int maxFrequency(int[] nums, int k) {
        Arrays.sort(nums);
        int l=0,total=0,max=1;
        for (int r=1;r<nums.length;r++){
            total=total+(nums[r]-nums[r-1])*(r-l);
            while (total>k){
                total-=nums[r]-nums[l];
                l++;
            }
            max=Math.max(max,r-l+1);
        }
        return max;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1838().maxFrequency(new int[]{1,2,4},5));
    }
}
